/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

package app.controllers.admin;

import app.Const;
import app.models.brand.Commodity;
import app.models.DaoKit;
import app.models.brand.Brand;
import com.github.sog.controller.BasicController;
import com.github.sog.controller.datatables.core.DatatablesCriterias;
import com.github.sog.libs.AppFunc;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.jfinal.plugin.activerecord.Page;

import java.util.List;

/**
 * <p>
 * .
 * </p>
 *
 * @author sagyf yang
 * @version 1.0 2014-04-16 21:24
 * @since JDK 1.6
 */
public class CommodityController extends BasicController {

    public static final String FORM_ATTR = "commodity";

    public void index(){
        long brandId = getParaToLong(0, 0l);
        if (brandId > 0) {
            Brand brand = Brand.dao.findById(brandId);
            setAttr("brand", brand);
            render("index.ftl");
        }
    }


    public void list() {
        long brandId = getParaToLong(0, 0l);
        final DatatablesCriterias criterias = getCriterias();
        Page<Commodity> parkingPage = Commodity.dao.datatable(criterias,brandId);

        renderDataTables(parkingPage, criterias);
    }


    public void create() {
        long brandId = getParaToLong(0, 0l);
        Commodity commodity = new Commodity();
        commodity.set("brand", brandId);
        setAttr(FORM_ATTR, commodity);
        setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);
        render("item.ftl");
    }


    public void edit() {
        final int id = getParaToInt(0, 0);
        Commodity commodity = Commodity.dao.findById(id);

        setAttr(FORM_ATTR, commodity);
        setAttr(Const.ACTION_ATTR, Const.EDIT_ACTION);
        render("item.ftl");
    }


    public void remove() {
        String remove_ids = getPara(Const.DATA_PARAM);
        List<String> ids = AppFunc.COMMA_SPLITTER.splitToList(remove_ids);
        if (DaoKit.batch_remove(SqlKit.sql("commodity.remove"), ids)) {
            renderSuccess();
        } else {
            renderError("删除出现错误");
        }
    }


    public void save() {
        Commodity commodity = getModel(Commodity.class);

        if (DaoKit.isNew(commodity)) {
            commodity.save();
        } else {
            commodity.update();
        }
        redirect("/admin/commodity/"+ commodity.getNumber("brand").longValue());
    }
}
